package com.example.myapplication.danmu

import android.view.ViewGroup

/**
 * @author: rongfeng
 * @date: 2022/3/11
 * @description
 */
class DanmuChannelController(val channelView: ViewGroup, val channel: Int, val mChannelController: ChannelController) : DanmuParts.DanmuPartsCallback {
    private val mDanmuPartsList = ArrayList<DanmuParts>()
    var isLooping = false

    fun setData(danmu: String) {
        var danmuParts: DanmuParts? = null
        mDanmuPartsList.forEach {
            if (it.isReusing()) {
                danmuParts = it
            }
        }
        if (danmuParts == null) {
            danmuParts = DanmuParts(channelView.context)
            danmuParts?.let {
                it.mDanmuPartsCallback = this
                mDanmuPartsList.add(it)
                channelView.addView(it.danmuView)
            }
        }
        danmuParts?.let {
            it.setData(danmu)
            it.start()
            isLooping = true
        }
    }

    @Synchronized
    override fun nextDanmu() {
        mChannelController.loopDanmu(channel)
    }

    override fun onAnimationRepeat() {
        var runCount = 0
        mDanmuPartsList.forEach {
            if (it.isRun) {
                runCount++
            }
        }
        if (runCount < 1) {
            isLooping = false
            mChannelController.loopDanmu(channel)
        }
    }

    interface ChannelController {
        fun loopDanmu(channel: Int)
    }

}